﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileSales.Website.Infrastructure.Messaging;
using MobileSales.Model.Params;
using System.ComponentModel.DataAnnotations;
using MobileSales.Website.Infrastructure;
using System.Web.Security;
using System.Threading;
using System.Globalization;

namespace MobileSales.Website.Controllers
{
    public class ControllerBase : Controller
    {
        #region Read only static data
        public static readonly string EmployeeIdKey = "__employeeId";
        public static readonly string TokenKey = "__token";
        public static readonly String CookieName = "MobileSalesWebsiteTicket"; 
        #endregion

        #region SetMessage

        protected void SetMessage(String content, MessageType type)
        {
            string idx = type.ToString() + "-messages";

            if (!this.TempData.ContainsKey(idx))
            {
                this.TempData[idx] = new List<Message>();
            }
            ((List<Message>)this.TempData[idx]).Add(new Message()
            {
                Content = content,
                Type = type
            });
        }

        #endregion

        #region GetParameters
        protected Dictionary<Param, string> GetParameters(FormCollection collection, Model.Params.ParamType paramType)
        {
            Dictionary<Param, string> dict = new Dictionary<Param, string>();
            ParamService.ParamServiceClient paramService = new ParamService.ParamServiceClient();
            paramService.AddValidationToken(this.Token);
            IEnumerable<Param> parameters = paramService.GetParamListByType(paramType);
            paramService.Close();
            foreach (var p in parameters)
            {
                string val = collection[p.Name];
                if (p.FieldType == FieldType.Dictionary)
                {
                    dict.Add(p, val);
                }
                else
                {
                    if (p.FieldType == FieldType.Boolean)
                        val = (val != null).ToString();
                    if (!string.IsNullOrEmpty(val))
                    {
                        if (p.MaxLength.HasValue && val.Length > p.MaxLength.Value && p.FieldType == FieldType.String)
                        {
                            throw new ValidationException(String.Format("Maximum {0} characters!", p.MaxLength.Value));
                        }
                        dict.Add(p, val);
                    }
                    else
                    {
                        if (p.IsRequired)
                        {
                            throw new ValidationException(String.Format("{0} is required!", p.DisplayName));
                        }
                    }
                }
            }
            return dict;
        }
        #endregion

        #region Token
        protected string Token
        {
            get
            {
                string cookie = GetTokenCookie();
                string token = null;
                if (cookie != null)
                {
                    token = cookie.Split(' ')[0];
                }
                return token;
            }
        }
        #endregion

        #region EmployeeId
        public int EmployeeId
        {
            get
            {
                string cookie = GetTokenCookie();
                int employeeId = 0;
                if (cookie != null)
                {
                    int.TryParse(cookie.Split(' ')[1], out employeeId);
                }
                return employeeId;
            }
        } 
        #endregion

        #region GetTokenCookie
        protected string GetTokenCookie()
        {
            try
            {
                String val = HttpContext.Request.Cookies.Get("MobileSalesWebsiteTicket").Value;
                return FormsAuthentication.Decrypt(val).UserData;
            }
            catch (NullReferenceException)
            {
                return null;
            }
        } 
        #endregion

        #region SaveTokenCookie
        protected void SaveTokenCookie(string token, int userId)
        {
            string userData = string.Format("{0} {1}", token, userId);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, CookieName,
                    DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                    true, userData);
            string hashedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(CookieName, hashedTicket);
            HttpContext.Response.Cookies.Add(cookie);
        } 
        #endregion

        #region ClearTokenCookie
        protected void ClearTokenCookie()
        {
            HttpCookie cookie = new HttpCookie(CookieName)
            {
                Expires = DateTime.Now.AddDays(-1)
            };
            HttpContext.Response.Cookies.Set(cookie);
        } 
        #endregion

        #region OnAuthorization
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            ViewData[EmployeeIdKey] = this.EmployeeId;
            ViewData[TokenKey] = this.Token;
        } 
        #endregion

        #region SetLanguage
        public ActionResult SetLanguage(string lang, string returnPath)
        {
            var cookie = new HttpCookie("lang", lang + "");
            cookie.Expires = DateTime.Now.AddYears(10);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            return Redirect(returnPath);
        } 
        #endregion
    }
}